/*
* @(#) FlowController.java 2018年02月23日
*
* Copyright 2010 NetEase.com, Inc. All rights reserved.
*/
package com.leo.m1802.d23;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 *
 * @author xuexiaolei
 * @version 2018年02月23日
 */
public class FlowController {
    static Semaphore s = new Semaphore(3);
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 50; i++) {
            exec.submit(new RequestTask(i));
        }
        exec.shutdown();
    }
    static class RequestTask implements Runnable{
        int n;
        RequestTask(int n){ this.n =n; }
        public void run() {
            try {
                s.acquire();
                System.out.println("线程："+ n +" 请求成功还剩余许可证个数：" + s.availablePermits());
                Thread.sleep(new Random().nextInt(1000));
                System.out.println("线程："+ n +" 执行完成退出.剩余许可证个数：" + s.availablePermits());
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
